from flask import g, render_template, current_app, request
from flask.views import MethodView
import json
from model import AlchemyJsonEncoder


class Panel(object):
    display_name = ""
    url = None
    table = None

    def get_table_view(self):
        if None == self.table:
            raise NotImplementedError()
        return Panel.get_view_func(self.table)
    
    def get_table_data_view(self):
        if None == self.table:
            raise NotImplementedError()
        return Panel.get_data_view_func(self.table)

    def get_url(self):
        if None == self.url:
            raise NotImplementedError()
        return self.url

    def full_url(self):
        return self.prifex + self.get_url()
    
    def data_url(self):
        return self.full_url() + "/data"
    
    def register(self, prifex, app):
        self.prifex = prifex
        app.add_url_rule(self.full_url(), self.display_name, self.get_table_view())
        setattr(self.table, "data_url", self.data_url())
        app.add_url_rule(self.data_url(),
            self.display_name + self.table.__class__.__name__, self.get_table_data_view())

    @classmethod
    def get_view_func(cls, table):
        def func():
            app = current_app._get_current_object()
            return render_template("table.html", dashboards=app.dashboards,
                table=table)
        return func

    @classmethod
    def get_data_view_func(cls, table):
        def func():
            page = int(request.args.get("page"))
            limit = int(request.args.get("limit"))
            _table = table()
            objects = _table.get_objects(page, limit)
            count = _table.get_objects_count()
            data = {"code":0,"msg":"","count":count,"data":objects}
            return json.dumps(data, cls=AlchemyJsonEncoder)
        return func